// 更新用户信息
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  try {
    const { _id, nickname, level, score } = event
    
    // 验证参数
    if (!_id) {
      return {
        success: false,
        error: '缺少用户ID'
      }
    }
    
    // 构建更新数据
    const updateData = {
      updateTime: new Date()
    }
    
    if (nickname !== undefined) updateData.nickname = nickname
    if (level !== undefined) updateData.level = level
    if (score !== undefined) updateData.score = parseInt(score)
    
    // 更新用户信息
    const result = await db.collection('users')
      .doc(_id)
      .update({
        data: updateData
      })
    
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('更新用户失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}
